<template>
  <div class="statistics-analysis">
    <!-- 页面标题和导出按钮 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">统计分析</h1>
        <p class="page-description">工作量仪表盘和数据分析</p>
      </div>
      <div class="header-actions">
        <el-dropdown @command="handleExport" split-button type="primary">
          导出数据
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="excel">导出Excel</el-dropdown-item>
              <el-dropdown-item command="pdf">导出PDF</el-dropdown-item>
              <el-dropdown-item divided command="current">当前视图数据</el-dropdown-item>
              <el-dropdown-item command="all">所有数据</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button :icon="Refresh" @click="refreshData">刷新数据</el-button>
      </div>
    </div>

    <!-- 时间范围选择器 -->
    <div class="time-filter">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        @change="handleDateRangeChange"
        style="width: 300px;"
      />
      <el-button-group class="quick-filters">
        <el-button 
          :type="quickFilter === 'today' ? 'primary' : 'default'"
          @click="setQuickFilter('today')"
        >今日</el-button>
        <el-button 
          :type="quickFilter === 'week' ? 'primary' : 'default'"
          @click="setQuickFilter('week')"
        >本周</el-button>
        <el-button 
          :type="quickFilter === 'month' ? 'primary' : 'default'"
          @click="setQuickFilter('month')"
        >本月</el-button>
        <el-button 
          :type="quickFilter === 'quarter' ? 'primary' : 'default'"
          @click="setQuickFilter('quarter')"
        >本季度</el-button>
      </el-button-group>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon total">
          <el-icon><Tickets /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ totalStats.totalTickets }}</div>
          <div class="stat-label">工单总数</div>
          <div class="stat-trend" :class="totalStats.ticketsTrend > 0 ? 'up' : 'down'">
            <el-icon><component :is="totalStats.ticketsTrend > 0 ? 'TrendCharts' : 'Bottom'" /></el-icon>
            {{ Math.abs(totalStats.ticketsTrend) }}%
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon completed">
          <el-icon><CircleCheck /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ totalStats.completedTickets }}</div>
          <div class="stat-label">已完成</div>
          <div class="stat-trend up">
            <el-icon><TrendCharts /></el-icon>
            {{ totalStats.completionRate }}%
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon sla">
          <el-icon><Timer /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ totalStats.slaCompliance }}%</div>
          <div class="stat-label">SLA达成率</div>
          <div class="stat-trend" :class="totalStats.slaCompliance >= 90 ? 'up' : 'down'">
            <el-icon><component :is="totalStats.slaCompliance >= 90 ? 'TrendCharts' : 'Bottom'" /></el-icon>
            {{ totalStats.slaCompliance >= 90 ? '优秀' : '需改进' }}
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon avg-time">
          <el-icon><Clock /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ totalStats.avgResolutionTime }}h</div>
          <div class="stat-label">平均处理时间</div>
          <div class="stat-trend down">
            <el-icon><Bottom /></el-icon>
            -12%
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 第一行图表 -->
      <div class="chart-row">
        <!-- 按用户统计工单数量 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3 class="chart-title">按用户统计工单数量</h3>
            <el-button-group size="small">
              <el-button 
                :type="userChartType === 'bar' ? 'primary' : 'default'"
                @click="userChartType = 'bar'"
              >柱状图</el-button>
              <el-button 
                :type="userChartType === 'pie' ? 'primary' : 'default'"
                @click="userChartType = 'pie'"
              >饼图</el-button>
            </el-button-group>
          </div>
          <div class="chart-content" ref="userChartRef"></div>
        </div>

        <!-- 工单状态分布 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3 class="chart-title">工单状态分布</h3>
          </div>
          <div class="chart-content" ref="statusChartRef"></div>
        </div>
      </div>

      <!-- 第二行图表 -->
      <div class="chart-row">
        <!-- 按任务类型统计 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3 class="chart-title">按任务类型统计</h3>
          </div>
          <div class="chart-content" ref="typeChartRef"></div>
        </div>

        <!-- 工单处理趋势 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3 class="chart-title">工单处理趋势</h3>
            <el-button-group size="small">
              <el-button 
                :type="trendPeriod === 'day' ? 'primary' : 'default'"
                @click="trendPeriod = 'day'"
              >按日</el-button>
              <el-button 
                :type="trendPeriod === 'week' ? 'primary' : 'default'"
                @click="trendPeriod = 'week'"
              >按周</el-button>
              <el-button 
                :type="trendPeriod === 'month' ? 'primary' : 'default'"
                @click="trendPeriod = 'month'"
              >按月</el-button>
            </el-button-group>
          </div>
          <div class="chart-content" ref="trendChartRef"></div>
        </div>
      </div>

      <!-- 第三行图表 -->
      <div class="chart-row">
        <!-- SLA达成情况 -->
        <div class="chart-card full-width">
          <div class="chart-header">
            <h3 class="chart-title">SLA达成情况分析</h3>
          </div>
          <div class="chart-content" ref="slaChartRef"></div>
        </div>
      </div>
    </div>

    <!-- 详细数据表格 -->
    <div class="data-table-section">
      <div class="section-header">
        <h3 class="section-title">详细统计数据</h3>
        <el-button :icon="Download" @click="exportTableData">导出表格</el-button>
      </div>
      
      <el-table
        :data="detailData"
        stripe
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="user" label="用户" width="120" />
        <el-table-column prop="totalTickets" label="总工单数" width="100" sortable />
        <el-table-column prop="completedTickets" label="已完成" width="100" sortable />
        <el-table-column prop="pendingTickets" label="待处理" width="100" sortable />
        <el-table-column prop="avgResolutionTime" label="平均处理时间(h)" width="140" sortable />
        <el-table-column prop="slaCompliance" label="SLA达成率" width="120" sortable>
          <template #default="{ row }">
            <el-tag :type="row.slaCompliance >= 90 ? 'success' : row.slaCompliance >= 70 ? 'warning' : 'danger'">
              {{ row.slaCompliance }}%
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="efficiency" label="工作效率" width="100">
          <template #default="{ row }">
            <el-progress 
              :percentage="row.efficiency" 
              :color="getEfficiencyColor(row.efficiency)"
              :stroke-width="6"
            />
          </template>
        </el-table-column>
        <el-table-column prop="lastActivity" label="最后活动时间" width="160" />
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Refresh, 
  Download, 
  Tickets, 
  CircleCheck, 
  Timer, 
  Clock,
  TrendCharts,
  Bottom
} from '@element-plus/icons-vue'

console.log('统计分析组件加载')

// 响应式数据
const loading = ref(false)
const dateRange = ref([])
const quickFilter = ref('month')
const userChartType = ref('bar')
const trendPeriod = ref('day')

// 图表引用
const userChartRef = ref()
const statusChartRef = ref()
const typeChartRef = ref()
const trendChartRef = ref()
const slaChartRef = ref()

// 统计数据
const totalStats = ref({
  totalTickets: 156,
  completedTickets: 128,
  slaCompliance: 87,
  avgResolutionTime: 4.2,
  ticketsTrend: 15.6,
  completionRate: 82.1
})

// 详细数据
const detailData = ref([
  {
    user: '张三',
    totalTickets: 45,
    completedTickets: 38,
    pendingTickets: 7,
    avgResolutionTime: 3.8,
    slaCompliance: 92,
    efficiency: 85,
    lastActivity: '2025-01-15 14:30'
  },
  {
    user: '李四',
    totalTickets: 38,
    completedTickets: 32,
    pendingTickets: 6,
    avgResolutionTime: 4.1,
    slaCompliance: 89,
    efficiency: 78,
    lastActivity: '2025-01-15 16:20'
  },
  {
    user: '王五',
    totalTickets: 42,
    completedTickets: 35,
    pendingTickets: 7,
    avgResolutionTime: 4.5,
    slaCompliance: 83,
    efficiency: 72,
    lastActivity: '2025-01-15 15:45'
  },
  {
    user: '赵六',
    totalTickets: 31,
    completedTickets: 23,
    pendingTickets: 8,
    avgResolutionTime: 5.2,
    slaCompliance: 74,
    efficiency: 65,
    lastActivity: '2025-01-15 13:15'
  }
])

// 页面初始化
onMounted(() => {
  console.log('统计分析页面初始化')
  initDateRange()
  loadCharts()
})

// 初始化日期范围
const initDateRange = () => {
  const today = new Date()
  const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate())
  dateRange.value = [
    lastMonth.toISOString().split('T')[0],
    today.toISOString().split('T')[0]
  ]
}

// 刷新数据
const refreshData = async () => {
  console.log('刷新统计数据')
  loading.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 重新加载图表
    loadCharts()
    
    ElMessage.success('数据刷新成功')
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败')
  } finally {
    loading.value = false
  }
}

// 处理导出
const handleExport = (command) => {
  console.log('导出数据:', command)
  
  const exportTypes = {
    excel: 'Excel格式',
    pdf: 'PDF格式',
    current: '当前视图数据',
    all: '所有数据'
  }
  
  ElMessage.info(`正在导出${exportTypes[command]}...`)
  
  // 模拟导出过程
  setTimeout(() => {
    ElMessage.success(`${exportTypes[command]}导出成功`)
  }, 2000)
}

// 导出表格数据
const exportTableData = () => {
  console.log('导出表格数据')
  ElMessage.info('正在导出表格数据...')
  
  setTimeout(() => {
    ElMessage.success('表格数据导出成功')
  }, 1500)
}

// 日期范围变更
const handleDateRangeChange = (dates) => {
  console.log('日期范围变更:', dates)
  quickFilter.value = ''
  loadCharts()
}

// 快速筛选
const setQuickFilter = (filter) => {
  console.log('设置快速筛选:', filter)
  quickFilter.value = filter
  
  const today = new Date()
  let startDate, endDate = today
  
  switch (filter) {
    case 'today':
      startDate = today
      break
    case 'week':
      startDate = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
      break
    case 'month':
      startDate = new Date(today.getFullYear(), today.getMonth(), 1)
      break
    case 'quarter':
      const quarter = Math.floor(today.getMonth() / 3)
      startDate = new Date(today.getFullYear(), quarter * 3, 1)
      break
  }
  
  dateRange.value = [
    startDate.toISOString().split('T')[0],
    endDate.toISOString().split('T')[0]
  ]
  
  loadCharts()
}

// 获取效率颜色
const getEfficiencyColor = (efficiency) => {
  if (efficiency >= 80) return '#67c23a'
  if (efficiency >= 60) return '#e6a23c'
  return '#f56c6c'
}

// 加载图表
const loadCharts = async () => {
  console.log('加载图表数据')
  
  await nextTick()
  
  // 这里应该使用真实的图表库如ECharts
  // 由于没有安装图表库，我们用模拟的方式显示
  
  if (userChartRef.value) {
    userChartRef.value.innerHTML = createMockChart('用户工单统计', userChartType.value)
  }
  
  if (statusChartRef.value) {
    statusChartRef.value.innerHTML = createMockChart('状态分布', 'pie')
  }
  
  if (typeChartRef.value) {
    typeChartRef.value.innerHTML = createMockChart('任务类型', 'doughnut')
  }
  
  if (trendChartRef.value) {
    trendChartRef.value.innerHTML = createMockChart('处理趋势', 'line')
  }
  
  if (slaChartRef.value) {
    slaChartRef.value.innerHTML = createMockChart('SLA分析', 'bar')
  }
}

// 创建模拟图表
const createMockChart = (title, type) => {
  const colors = ['#3498db', '#e74c3c', '#2ecc71', '#f39c12', '#9b59b6']
  const typeNames = {
    bar: '柱状图',
    pie: '饼图',
    doughnut: '环形图',
    line: '折线图'
  }
  
  return `
    <div style="
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      border-radius: 8px;
      color: #666;
      text-align: center;
    ">
      <div style="font-size: 18px; font-weight: 600; margin-bottom: 12px;">${title}</div>
      <div style="font-size: 14px; margin-bottom: 16px;">${typeNames[type] || '图表'}</div>
      <div style="display: flex; gap: 8px; margin-bottom: 12px;">
        ${colors.map(color => `<div style="width: 20px; height: 20px; background: ${color}; border-radius: 3px;"></div>`).join('')}
      </div>
    </div>
  `
}

// 监听图表类型变化
watch([userChartType, trendPeriod], () => {
  loadCharts()
})
</script>

<style scoped>
.statistics-analysis {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-left {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-description {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 时间筛选 */
.time-filter {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.quick-filters {
  display: flex;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.stat-card {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.completed {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.sla {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.avg-time {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 8px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
}

.stat-trend.up {
  color: #10b981;
}

.stat-trend.down {
  color: #ef4444;
}

/* 图表容器 */
.charts-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.chart-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.chart-card {
  background: #ffffff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-card.full-width {
  grid-column: 1 / -1;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e7eb;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin: 0;
}

.chart-content {
  height: 300px;
  min-height: 300px;
}

/* 数据表格区域 */
.data-table-section {
  background: #ffffff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e7eb;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #374151;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .chart-row {
    grid-template-columns: 1fr;
  }
  
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .time-filter {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .stat-card {
    padding: 16px;
  }
  
  .chart-card {
    padding: 16px;
  }
}

/* 深色主题适配 */
@media (prefers-color-scheme: dark) {
  .stat-card,
  .chart-card,
  .data-table-section {
    background: #1f2937;
    border: 1px solid #374151;
  }
  
  .page-title,
  .chart-title,
  .section-title {
    color: #f9fafb;
  }
  
  .page-description {
    color: #d1d5db;
  }
  
  .stat-value {
    color: #f9fafb;
  }
  
  .stat-label {
    color: #9ca3af;
  }
}
</style>
